package cn.pugle.base;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * 不要让标准输出和标准错误堵住...
 * https://wiki.sei.cmu.edu/confluence/display/java/FIO07-J.+Do+not+let+external+processes+block+on+IO+buffers
 * 进程in java
 * Created by tzp on 16/9/5.
 */
public class ProcessTest {
    public static void main(String[] args) throws Exception {
        Process process = Runtime.getRuntime().exec("sleep 20s");

        streamHandle(process.getInputStream());
        streamHandle(process.getErrorStream());

        try {
//            int i = process.waitFor();
            int exitValue = process.exitValue();
            System.out.println(exitValue);
        } catch (IllegalThreadStateException e) {
            throw new Exception("Strange! Stream End and failed to get appId, but process has not yet terminated, cant get exit code");
        }

//        ProcessBuilder processBuilder = new ProcessBuilder();
//        Process process1 = processBuilder.start();
    }

    public static void streamHandle(InputStream stream) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
        String line;
        try {
            while ((line = reader.readLine()) != null) {
                System.out.println("Stdout: " + line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
